﻿using System.Net;
using System.Net.Sockets;

namespace HCore
{
    public class UdpSocket
    {
        private Socket _socket;

        public UdpSocket()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        }

        public void Bind(EndPoint endPoint)
        {
            _socket.Bind(endPoint);
        }

        public int SendTo(byte[] bytes, int length, EndPoint remoteEndPoint)
        {
            return _socket.SendTo(bytes, length, SocketFlags.None, remoteEndPoint);
        }

        public virtual ReceivedPacket ReceiveFrom()
        {
            if (_socket.Available > 0)
            {
                byte[] bytes = new byte[1500];
                EndPoint fromEnd = new IPEndPoint(IPAddress.Any, 0);
                int readByteCount = _socket.ReceiveFrom(bytes, ref fromEnd);
                return new ReceivedPacket(new InputMemoryBitStream(bytes, readByteCount), fromEnd);
            }
            
            return null;
        }
        
        public void Dispose()
        {
            _socket.Close();
            _socket = null;
        }
    }
}